package io.gps.datatransfer;

import java.net.InetSocketAddress;

import io.gps.datatransfer.codec.DevHandler;
import io.gps.datatransfer.utils.SysDef;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.DatagramSessionConfig;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;

/**
 * udp接收端初始化
 * @author bcs
 * @version 2.0, $Date:  2020-11-26 13:04:48 $
 */
public class UDPController {
	private Logger logger = Logger.getLogger(getClass());
	/**
	 * udp接收控制端
	 */
	public static NioDatagramAcceptor acceptor;

	public UDPController(ProtocolCodecFactory codecFactory) throws Exception{
		init(codecFactory);
	}
	DevHandler handler;
	ProtocolCodecFactory codecFactory ;
	/**
	 * 初始化udp接收设置
	 * @param codecFactory 解码容器
	 * @throws Exception
	 */
	public void init(ProtocolCodecFactory codecFactory) throws Exception{
		acceptor = new NioDatagramAcceptor();
		this.codecFactory = codecFactory;
		handler = new DevHandler();
		acceptor.setHandler(handler);
		acceptor.getFilterChain().addLast("protocol",
				new ProtocolCodecFilter(codecFactory));
		DatagramSessionConfig dcfg = acceptor.getSessionConfig();
		dcfg.setReuseAddress(true);
		dcfg.setMaxReadBufferSize(SysDef.MaxReadBufferSize*10);
		dcfg.setIdleTime(IdleStatus.BOTH_IDLE,SysDef.SESSION_HAND_TIMEOUT/2);

		bind();

	}
	/**
	 * 端口绑定
	 * @throws Exception
	 */
	public void bind() throws Exception{
		acceptor.bind(new InetSocketAddress(SysDef.LOCAL_DEV_PORT));
		logger.info("udp listen to "+SysDef.LOCAL_DEV_PORT);
	}
	public void rebind() throws Exception{
		if(acceptor!=null && (System.currentTimeMillis()-getLastRecvTime())>60000){
			try{
				logger.info("UDP长时间未接收数据，重新绑定端口---");
				acceptor.dispose();
			}catch(Exception e){
				handler=null;
				acceptor=null;
			}
			init(codecFactory);
		}

	}
	public long getLastRecvTime(){
		return handler.getLastRecvTime();
	}
}
